<template>
  <div class="test_box_network">
    <div class="list">
      <div
        class="box"
        :class="index == 0 ? 'active' : ' '"
        v-for="(item, index) in dataList"
        :key="index"
      >
        <div class="name">
          <span>{{ item.name }}</span>
        </div>
        <div class="value">
          <span>{{ item.value }}</span>
        </div>
        <div class="status">
          <div class="success" v-if="item.status == 1">
            <div class="icon"></div>
            <div class="text">正常</div>
          </div>
          <div class="error" v-if="item.status == 2">
            <div class="icon"></div>
            <div class="text">异常</div>
            <div class="tips">
              <span @click="showTips(index)">查看建议</span>
              <div class="popup" v-if="item.tipsPopup">
                <div class="triangle"></div>
                <div class="text">
                  <p>1. 建议使用有线网络连接或在更好的网络环境下直播</p>
                  <p>2. 请检测您的网络连接是否正常</p>
                </div>
              </div>
            </div>
          </div>
          <div class="success" v-if="item.status == 3">
            <img
              class="loading"
              src="@/assets/img/testing/loading.gif"
              alt=""
            />
            <div class="text">正在检测</div>
          </div>
          <span v-if="index == 0">{{ item.status }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import TRTC from "trtc-js-sdk";

export default {
  data() {
    return {
      tipsPopup: false,
      dataList: [
        {
          name: "主要检测指标",
          value: "检测结果",
          status: "状态",
        },
        { name: "操作系统检测", value: "", status: 3, tipsPopup: false },
        { name: "浏览器兼容测试", value: "", status: 3, tipsPopup: false },
        { name: "网速检测", value: "", status: 3, tipsPopup: false },
        { name: "webRTC", value: "", status: 3, tipsPopup: false },
      ],
      sysStatus: false,
    };
  },
  mounted() {
    //   获取操作系统
    this.getOsInfo();
    // 检测兼容性/webRTC兼容性
    this.checkCompatible();
    // 检测网速
    this.checkSpeed();
  },
  watch: {
    dataList: {
      //深度监听，可监听到对象、数组的变化
      handler(val, oldVal) {
        let sys = false;
        for (let i in val) {
          if (i > 0) {
            if (val[i].status == 1) {
              sys = true;
            } else {
              sys = false;
              break;
            }
          }
        }
        this.$emit("sysStatus", sys);
        this.sysStatus = sys;
      },
      deep: true, //true 深度监听
    },
  },
  destroyed() {},
  methods: {
    //   获取操作系统
    getOsInfo() {
      let userAgent = navigator.userAgent.toLowerCase();
      let name = "";
      let version = "";
      if (userAgent.indexOf("win") > -1) {
        name = "Windows";
        if (userAgent.indexOf("windows nt 5.0") > -1) {
          version = "Windows 2000";
        } else if (
          userAgent.indexOf("windows nt 5.1") > -1 ||
          userAgent.indexOf("windows nt 5.2") > -1
        ) {
          version = "Windows XP";
        } else if (userAgent.indexOf("windows nt 6.0") > -1) {
          version = "Windows Vista";
        } else if (
          userAgent.indexOf("windows nt 6.1") > -1 ||
          userAgent.indexOf("windows 7") > -1
        ) {
          version = "Windows 7";
        } else if (
          userAgent.indexOf("windows nt 6.2") > -1 ||
          userAgent.indexOf("windows 8") > -1
        ) {
          version = "Windows 8";
        } else if (userAgent.indexOf("windows nt 6.3") > -1) {
          version = "Windows 8.1";
        } else if (
          userAgent.indexOf("windows nt 6.2") > -1 ||
          userAgent.indexOf("windows nt 10.0") > -1
        ) {
          version = "Windows 10";
        } else {
          version = "Unknown";
        }
      } else if (userAgent.indexOf("iphone") > -1) {
        name = "Iphone";
      } else if (userAgent.indexOf("mac") > -1) {
        name = "Mac";
      } else if (
        userAgent.indexOf("x11") > -1 ||
        userAgent.indexOf("unix") > -1 ||
        userAgent.indexOf("sunname") > -1 ||
        userAgent.indexOf("bsd") > -1
      ) {
        name = "Unix";
      } else if (userAgent.indexOf("linux") > -1) {
        if (userAgent.indexOf("android") > -1) {
          name = "Android";
        } else {
          name = "Linux";
        }
      } else {
        name = "Unknown";
      }
      this.dataList[1].value = name;
      this.dataList[1].status = 1;
    },
    // 检测是否兼容
    checkCompatible() {
      // 判断浏览器型号
      navigator.sayswho = (function () {
        var ua = navigator.userAgent,
          tem,
          M =
            ua.match(
              /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i
            ) || [];
        if (/trident/i.test(M[1])) {
          tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
          return "IE " + (tem[1] || "");
        }
        if (M[1] === "Chrome") {
          tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
          if (tem != null)
            return tem.slice(1).join(" ").replace("OPR", "Opera");
        }
        M = M[2]
          ? [M[1], M[2]]
          : [navigator.appName, navigator.appVersion, "-?"];
        if ((tem = ua.match(/version\/(\d+)/i)) != null) M.splice(1, 1, tem[1]);
        return M.join(" ");
      })();
      this.dataList[2].value = navigator.sayswho;
      TRTC.checkSystemRequirements().then((checkResult) => {
        if (!checkResult.result) {
          // 不兼容
          console.log(
            "checkResult",
            checkResult.result,
            "checkDetail",
            checkResult.detail
          );
          this.dataList[2].status = 2;
          // webRTC
          this.dataList[4].status = 2;
          this.dataList[4].value = "不支持";
        } else {
          // 兼容
          this.dataList[2].status = 1;
          // webRTC
          this.dataList[4].value = "支持";
          this.dataList[4].status = 1;
        }
      });
    },
    // 检测网速
    checkSpeed() {
      function measureBW(fn, time) {
        time = time || 1;
        var startTime, endTime, fileSize;
        var count = time;
        var _this = this;
        function measureBWSimple() {
          var xhr = new XMLHttpRequest();

          xhr.onreadystatechange = () => {
            if (xhr.readyState === 4 && xhr.status === 200) {
              if (!fileSize) {
                fileSize = xhr.responseText.length;
              }
              count--;
              if (count <= 0) {
                endTime = Date.now();
                var speed =
                  (fileSize * time) / ((endTime - startTime) / 1000) / 1024;
                fn && fn(Math.floor(speed));
              }
            } else {
              fn && fn(0);
            }
          };
          xhr.open(
            "GET",
            "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2384125981,3446294493&fm=26&gp=0.jpg",
            true
          );
          xhr.send();
        }
        startTime = Date.now();
        for (var x = time; x > 0; x--) {
          measureBWSimple();
        }
      }
      let num = 0;
      measureBW((speed) => {
        speed = speed - 0;
        num = num + speed;
        this.dataList[3].value = speed + " KB/sec";
      }, 10);

      setTimeout(() => {
        if (num / 10 > 1) {
          this.dataList[3].status = 1;
          this.dataList[3].value = num / 10 + " KB/sec";
        } else {
          this.dataList[3].status = 2;
          this.dataList[3].value = num / 10 + " KB/sec";
        }
      }, 100);
    },
    showTips(index) {
      for (let i in this.dataList) {
        if (i != index) {
          this.dataList[i].tipsPopup = false;
        }
      }
      this.dataList[index].tipsPopup = !this.dataList[index].tipsPopup;
    },
  },
};
</script>

<style lang="scss" scoped>
.test_box_network {
  box-sizing: border-box;
  .list {
    width: 100%;
    margin-bottom: 190px;
    .box {
      display: flex;
      justify-content: space-between;
      width: 100%;
      line-height: 45px;
      background: #ffffff;
      border-bottom: solid 1px rgba(0, 0, 0, 0.06);
      &.active {
        background: rgba(0, 0, 0, 0.02);
        .name,
        .value,
        .status {
          font-weight: 500;
          color: rgba(0, 0, 0, 0.85);
        }
      }
      .name,
      .value,
      .status {
        font-size: 14px;
        font-weight: 400;
        color: rgba(0, 0, 0, 0.65);

        width: 100%;
        display: flex;
        align-items: left;
        justify-content: flex-start;
      }
      .name {
        padding-left: 70px;
      }
      .status {
        .success,
        .error {
          display: flex;
          align-items: center;
          .loading {
            width: 15px;
            height: 15px;
            margin-right: 8px;
          }
          .icon {
            width: 8px;
            height: 8px;
            background: #52c41a;
            border-radius: 50%;
            margin-right: 8px;
          }
          .text {
            font-size: 14px;
            font-weight: 400;
            color: rgba(0, 0, 0, 0.65);
          }
        }
        .error {
          .icon {
            background: #e94642;
          }
          .tips {
            margin-left: 24px;
            font-size: 12px;
            font-weight: 400;
            color: #475aa7;
            position: relative;
            span {
              cursor: pointer;
            }
            .popup {
              .triangle {
                width: 0;
                height: 0;
                border-left: 5px solid transparent;
                border-right: 5px solid transparent;
                border-bottom: 6px solid #eceef6;
                margin: 0 auto;
              }
              position: absolute;
              bottom: -50px;
              width: 310px;
              height: 63px;
              left: 50%;
              transform: translate(-50%, 0); /*50%为自身尺寸的一半*/
              .text {
                background: #eceef6;
                padding: 14px 16px;
                padding-top: 8px;
                p {
                  margin: 0;
                  padding: 0;
                  font-size: 12px;
                  font-weight: 400;
                  color: rgba(0, 0, 0, 0.65);
                  line-height: 18px;
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>

